import * as http from 'http';
import * as url from 'url';
import PdfExportPlugin from './main';

export class PdfExportServer {
    private server: http.Server | null = null;
    private port: number;
    private plugin: PdfExportPlugin;

    constructor(port: number, plugin: PdfExportPlugin) {
        this.port = port;
        this.plugin = plugin;
    }

    start(): Promise<void> {
        return new Promise((resolve, reject) => {
            if (this.server) {
                reject(new Error('Server already running'));
                return;
            }

            this.server = http.createServer((req, res) => {
                this.handleRequest(req, res);
            });

            this.server.listen(this.port, () => {
                console.log(`PDF Export Server running on port ${this.port}`);
                resolve();
            });

            this.server.on('error', (err) => {
                reject(err);
            });
        });
    }

    stop(): Promise<void> {
        return new Promise((resolve, reject) => {
            if (!this.server) {
                resolve();
                return;
            }

            this.server.close((err) => {
                if (err) {
                    reject(err);
                } else {
                    this.server = null;
                    console.log('PDF Export Server stopped');
                    resolve();
                }
            });
        });
    }

    private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
        const parsedUrl = url.parse(req.url || '', true);
        const path = parsedUrl.pathname;

        // 设置CORS头
        res.setHeader('Access-Control-Allow-Origin', '*');
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

        // 处理预检请求
        if (req.method === 'OPTIONS') {
            res.writeHead(200);
            res.end();
            return;
        }

        try {
            if (path === '/convert' && req.method === 'POST') {
                await this.handleConvertRequest(req, res);
            } else if (path === '/health' && req.method === 'GET') {
                this.handleHealthRequest(res);
            } else {
                this.handleNotFound(res);
            }
        } catch (error) {
            this.handleError(res, error);
        }
    }

    private async handleConvertRequest(req: http.IncomingMessage, res: http.ServerResponse) {
        let body = '';

        req.on('data', chunk => {
            body += chunk.toString();
        });

        req.on('end', async () => {
            try {
                const requestData = JSON.parse(body);
                const markdown = requestData.markdown;
                const filename = requestData.filename || 'document.pdf';

                if (!markdown) {
                    res.writeHead(400, { 'Content-Type': 'application/json' });
                    res.end(JSON.stringify({ error: 'Missing markdown parameter' }));
                    return;
                }

				console.log(123)
				console.log(this.plugin)
                // 使用插件的转换功能
                const pdfBuffer = await this.plugin.convertMarkdownToPdf(markdown, filename);
				console.log(456)


                // 返回PDF文件

                res.writeHead(200, {
                    'Content-Type': 'application/pdf',
                    'Content-Disposition': `attachment; filename="${filename}"`
                });
                res.end(Buffer.from(pdfBuffer));
            } catch (error) {
                this.handleError(res, error);
            }
        });
    }

    private handleHealthRequest(res: http.ServerResponse) {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({
            status: 'ok',
            timestamp: new Date().toISOString(),
            service: 'pdf-export-server',
            port: this.port
        }));
    }

    private handleNotFound(res: http.ServerResponse) {
        res.writeHead(404, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Not found' }));
    }

    private handleError(res: http.ServerResponse, error: any) {
        console.error('Server error:', error);
        res.writeHead(500, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify({ error: 'Internal server error', message: error.message }));
    }
}
